package com.java2207.group1.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.java2207.group1.bo.CasesBo;
import com.java2207.group1.bo.DrugStorageBo;
import com.java2207.group1.common.LayuiPageVo;
import com.java2207.group1.common.R;
import com.java2207.group1.listener.CasesConsultListener;
import com.java2207.group1.listener.DrugStorageListener;
import com.java2207.group1.pojo.Cases;
import com.java2207.group1.pojo.DrugStorage;
import com.java2207.group1.service.DrugStorageService;
import com.java2207.group1.util.OssUtil;
import com.java2207.group1.vo.casesult.CasesBarVo;
import com.java2207.group1.vo.casesult.CasesPieVo;
import com.java2207.group1.vo.drugstorage.DrugPieVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Lenovo 2022/7/26 12:06
 */
@RestController
@RequestMapping("/drug")
public class DrugStorageController {

    @Autowired
    private DrugStorageService drugStorageService;

    /**
     * 分页查询内容
     * @param params
     * @return
     */
    @RequestMapping("/drugList")
    public LayuiPageVo<DrugStorage> drugLayuiPageData(@RequestParam Map<String, Object> params){
        return drugStorageService.drugLayuiPageData(params);
    }


    /**
     * 查询所有药品信息
     * @return
     */
    @RequestMapping("/selectAllDrug")
    public R selectAllDrug(){
        List<DrugStorage> list = drugStorageService.selectAllDrug();
        return R.ok().data("allDrug",list);
    }


    /**
     * 添加药品信息
     * @param drug
     * @return
     */
    @RequestMapping("/addDrug")
    public R addDrug(DrugStorage drug){
        int result = drugStorageService.addDrug(drug);
        if(result ==1){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     * 根据Id删除药品信息
     * @param id
     * @return
     */
    @RequestMapping("/deleteDrug")
    public R deleteDrug(Integer id){
        int result = drugStorageService.deleteDrug(id);
        if (result ==1){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     * 根据Id删除多条药品信息
     * @param ids
     * @return
     */
    @RequestMapping("/deleteDrugByIds")
    public R deleteDrugByIds(String ids){
        int result = drugStorageService.deleteDrugByIds(ids);
        if (result > 0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     * 修改药品信息
     * @param drug
     * @return
     */
    @RequestMapping("/updateDrug")
    public R updateDrug(DrugStorage drug){
        int result = drugStorageService.updateDrug(drug);
        if (result ==1){
            return R.ok();
        }else {
            return R.error();
        }
    }


    /**
     *  药品产地分析  饼图
     * @return
     */
    @RequestMapping("/echartsPie")
    public R echartsPie() {
        List<DrugPieVo> list = drugStorageService.drugPieData();
        return R.ok().data("pie", list);
    }


    //上传图片
    // springmvc 的 文件上传组件
    @RequestMapping("/upload")
    public R uploadPic(MultipartFile file) throws IOException {
        //避免预检请求报错  这里有个 if  判断
        if (file != null) {
            //得到文件名
            String originalFilename = file.getOriginalFilename();
            // 将文件转为输入流
            InputStream inputStream = file.getInputStream();
            String url = OssUtil.uploadFile(inputStream, originalFilename);

            //把文件 url 写给前端
            return R.ok().data("url", url);
        }
        return R.ok();
    }


    /**
     * 下载excel 模板
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/templateDownload")
    public void templateDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        //读取服务器上的模板文件 写到浏览器
        //得到模板文件的路径
        String realPath = request.getServletContext().getRealPath("/template/药品信息模板.xlsx");

        //根据文件路径 创建File 对象
        File file = new File(realPath);

        // 把File  对象转为 字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);

        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String fileName = URLEncoder.encode("药品信息模板", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        // 把字节数组 输出到浏览器
        outputStream.write(bytes);

        outputStream.close();
    }

    @Autowired
    private DrugStorageListener drugStorageListener;

    /**
     * 读取excel 文件数据 存到数据库中
     * 导入药品信息
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/import")
    public R importExcel(MultipartFile file) throws IOException {
        // 避免遇见请求报错
        if (file != null) {
            /**
             * 参数1  文件流
             * 参数2  读取到的数据封装到哪个数据类型中
             * 参数3  监听器  每读取一行数据 就会调用监听器中的 invoke  方法
             * */
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), DrugStorageBo.class, drugStorageListener);
            // 得到 sheet 对象
            ExcelReaderSheetBuilder sheet = read.sheet();
            // 读取sheet
            sheet.doRead();

        }
        return R.ok();
    }


    /**
     * 导出药品信息数据
     * 把满足条件的数据 查询出来  写到excel 中  ，把excel 写到浏览器
     *
     * @param params
     * @param response
     * @throws IOException
     */
    @RequestMapping("/export")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws IOException {

        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String fileName = URLEncoder.encode("药品信息导出", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriterBuilder write = EasyExcel.write(outputStream, DrugStorageBo.class);

        // 得到 sheet 对象
        ExcelWriterSheetBuilder sheet = write.sheet();

        //准备满足条件的集合数据
        List<DrugStorageBo> subjcts = drugStorageService.druExcelData(params);

        // 把这个集合数据 写到 输出流
        sheet.doWrite(subjcts);
    }



}
